import java.util.*;

public class binary_tree_level_order_traversal {
    //BFS
    public List<List<Integer>> levelOrder(TreeNode root) {

        List<List<Integer>> ans= new ArrayList<>();
        Queue<TreeNode> queue=new LinkedList<>();
        if (root != null) {
            queue.add(root);
        }
        while(!queue.isEmpty()){
            int n=queue.size();
            List<Integer> level=new ArrayList<>();
            for(int i=0;i<n;i++){
                TreeNode node= queue.poll();
                level.add(node.val);
                if(node.left!=null) queue.add(node.left);
                if(node.right!=null) queue.add(node.right);
            }
            ans.add(level);
        }
        return ans;
    }
}
